package com.xybbs.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xybbs.entity.Tips;
import com.xybbs.entity.Users;
import com.xybbs.service.TipsService;
import com.xybbs.service.UsersService;

@RequestMapping("user")
@Controller
public class UserController {
	
	@Autowired
	UsersService usersService;
	@Autowired
	TipsService tipsService;
	
	@RequestMapping("toSignUpPage.do")
	public String toSignUpPage() {
		return "signUp";
	}
	
	@RequestMapping("userSignUp.do")
	public String userSingUp(Users user,HttpServletRequest req) {
		Users result = usersService.Verify(user.getUserName());
		if(result!=null) {
			req.setAttribute("msg", "帐号不可用");
			return "signUp";
		}else {
			usersService.signUp(user);
			return "redirect:toLoginPage.do";
		}
	}
	
	@RequestMapping("toLoginPage.do")
	public String toLoginPage() {
		return "login";
	}
	
	@RequestMapping("userLogin.do")
	public String userLogin(String userName,String userPassword,HttpServletRequest req) {
		Users result = usersService.login(userName, userPassword);
		if(result.getUserName().equals(userName) ){
			req.getSession().setAttribute("user", result);
			List<Tips> list = tipsService.checkAllWithUser();
			req.setAttribute("tips", list);
			return "main";
		}else {
			req.setAttribute("msg", "帐号或密码错误");
			return "404";
		}	
	}
	
	@RequestMapping("/getUserInfo.do")
	public String getUserInfoString(String userId,HttpServletRequest req) {
		Users result = usersService.getUserInfo(userId);
		req.setAttribute("userObject", result);
		return "userInfo";
	}
	
	@RequestMapping("toUpdateUserInfoPage.do")
	public String toUpdateUserInfoPage(String userId,HttpServletRequest req) {
		Users result = usersService.getUserInfo(userId);
		req.setAttribute("userObject", result);
		return "update_userInfo";
	}
	
	@RequestMapping("updateUserInfo")
	public String updateUserInfo(String userId,String userPassword,String userNick,HttpServletRequest req,RedirectAttributes attr) {
		Users result = usersService.checkUserByNick(userNick,userId);
		
		if(result!=null) {
			req.setAttribute("msg", "昵称不可用");
			return "404";
		}else{
			usersService.updateUser(userPassword, userNick, userId);
			//�ض���toUpdateUserInfoPage.do�����ϲ���
			attr.addAttribute("userId",userId);
			return "redirect:getUserInfo.do";
		}
	}
	
	@RequestMapping("userSignOut.do")
	public String userSignOut(HttpSession session) {
		session.invalidate();
		return "/index";
	}

}
